package com.example.questionanswersystem.service;

import com.example.questionanswersystem.entity.Question;
import com.example.questionanswersystem.repository.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionService {

    @Autowired
    private PdfService pdfService;

    @Autowired
    private QuestionRepository questionRepository;

    @Async
    public void uploadAndParsePdf(byte[] fileBytes, String originalFilename) {
        try (InputStream inputStream = new ByteArrayInputStream(fileBytes)) {
            List<Question> questions = pdfService.parseQuestions(inputStream, originalFilename);
            questionRepository.saveAll(questions);
        } catch (IOException e) {
            // Basic error handling for async method
            e.printStackTrace();
        }
    }

    public List<Question> searchByKeyword(String keyword) {
        // Reformat keyword for boolean mode search
        // +: must be present. A leading + on each word means all words must be found.
        String booleanModeKeyword = Arrays.stream(keyword.split("\\s+"))
                .map(term -> "+" + term)
                .collect(Collectors.joining(" "));
        return questionRepository.findByKeyword(booleanModeKeyword);
    }
} 